package com.zy.field;

import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

public class FlexibleObjectSerializer implements ObjectSerializer {
    private boolean useCustomNames;

    public FlexibleObjectSerializer(boolean useCustomNames) {
        this.useCustomNames = useCustomNames;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName,
                     Type fieldType, int features) {
        if (object == null) {
            serializer.writeNull();
            return;
        }

        // 使用基础写入方法替代 writeStartObject() 等
        try {
            serializer.getWriter().write('{');
        } catch (Exception e) {
            // 降级处理
            serializer.write(object);
            return;
        }

        Class<?> clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        boolean first = true;

        for (Field field : fields) {
            try {
                field.setAccessible(true);
                String fieldNameStr = field.getName();
                Object fieldValue = field.get(object);

                // 获取字段名映射（优先使用 @JSONField 注解）
                String jsonFieldName = getJsonFieldName(field, fieldNameStr);
                String finalFieldName = useCustomNames ? jsonFieldName : fieldNameStr;

                if (!first) {
                    serializer.getWriter().write(',');
                }

                // 写入字段名
//                serializer.writeFieldName(finalFieldName);
//                serializer.writeWithFieldName(fieldValue,finalFieldName);
                serializer.getWriter().write('"');
                serializer.getWriter().write(finalFieldName);
                serializer.getWriter().write('"');
                serializer.getWriter().write(':');

                // 处理嵌套对象或基本类型
                if (fieldValue != null && isComplexObject(fieldValue)) {
                    write(serializer, fieldValue, finalFieldName, fieldValue.getClass(), 0);
                } else if (fieldValue instanceof java.util.List) {
                    // 处理 List 类型
                    serializer.write((java.util.List<?>) fieldValue);
                } else {
                    serializer.write(fieldValue);
                }

                first = false;
            } catch (IllegalAccessException e) {
                // 忽略无法访问的字段
            }
        }

        try {
            serializer.getWriter().write('}');
        } catch (Exception e) {
            // 最后降级
            serializer.write(object);
        }
    }

    private String getJsonFieldName(Field field, String defaultName) {
        JSONField jsonField = field.getAnnotation(JSONField.class);
        if (jsonField != null && !jsonField.name().isEmpty()) {
            return jsonField.name();
        }
        return defaultName;
    }

    private boolean isComplexObject(Object obj) {
        Class<?> clazz = obj.getClass();
        String className = clazz.getName();
        return !(clazz.isPrimitive() ||
                className.startsWith("java.lang") ||
                className.startsWith("java.util") ||
                obj instanceof Number ||
                obj instanceof Boolean ||
                obj instanceof Character ||
                obj instanceof String);
    }
}
